package cn.dreamblog.controller;

import cn.dreamblog.pojo.Goodstatus;
import cn.dreamblog.service.BlogService;
import cn.dreamblog.service.GoodstatusService;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/goodstatus")
public class GoodstatusController {
    @Resource
    private GoodstatusService goodService;
    @Resource
    private BlogService blogService;

    @RequestMapping("/goods.do")
    @ResponseBody
    public String nice(Integer user_id, Integer blog_id) {
        Map<String, Object> map = new HashMap<>();
        //查询是否有该用户的点赞记录
        Goodstatus goodstatus = goodService.findGoodstatus(new Goodstatus(user_id, blog_id));
        if (goodstatus != null) {
            //如果不为空（有记录），修改用户的点赞状态
            if (goodstatus.getStatus() == 1) {
                //根据博客id和用户id修改点赞状态
                map.put("goodStatus", "successed");
            } else if (goodstatus.getStatus() == 0) {
                //根据博客id和用户id修改点赞状态
                int i = goodService.updateGoodstatus(blog_id, user_id, 1);
            }
        } else {
            //如果为空（没记录），执行增加操作，增加记录,列status增加默认为1
            int i = goodService.insertGood(new Goodstatus(user_id, blog_id));
            if (i > 0) {
                map.put("insertStatus", "successed");
                map.put("goodStatus", "failed");
            } else {
                map.put("insertStatus", "failed");
            }
        }
        //查询点赞数
        int goodCount = goodService.selectGoods(blog_id);
        map.put("goodCount", goodCount);
        if ((String)map.get("goodstatus") == "failed" || (String)map.get("insertStatus") == "successed"){
            blogService.updateGoodCount(blog_id, goodCount);
        }
        //点赞数存储到页面
        return JSON.toJSONString(map);
    }

}
